package com.uni.controller;

import com.alibaba.fastjson.JSON;
import com.uni.base.RestResponse;
import com.uni.base.SystemCodeEnum;
import com.uni.dao.RoleMapper;
import com.uni.pojo.User;
import com.uni.service.RoleService;
import com.uni.service.UserService;
import lombok.extern.log4j.Log4j2;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.util.HashMap;

/**
 * Author:      Unirithe/Mr.Chao
 * CSDN:        https://blog.csdn.net/Unirithe
 * CreatedTime:  2022/1/29 17:57
 **/
@Log4j2
@Controller
public class LoginController {
    @Autowired
    private UserService userService;
    @Autowired
    private RoleService roleService;
    @GetMapping("/login.html")
    public String toLogin(){return "login";}
    @GetMapping("/user/logout")
    public String loginOut(HttpServletRequest request, HttpServletResponse response, HttpSession session){
        Subject subject = SecurityUtils.getSubject();
        subject.logout();
        return "redirect:login.html";
    }

    @PostMapping("/login")
    @ResponseBody
    private String login(User user,
                         @RequestParam(value = "checkcode") String inputCode,
                         HttpSession session){
        String realCode = (String) session.getAttribute("code");
        if(!realCode.equals(inputCode)) return RestResponse.fail("验证码错误!").toJSONString();
        User userInfo = userService.login(user);
        session.setAttribute("userInfo", userInfo);
        if(userInfo == null)
            return RestResponse.fail(SystemCodeEnum.AuthError.getCode(), SystemCodeEnum.AuthError.getMessage()).toJSONString();
        else
            return RestResponse.ok().toJSONString();
    }

    @GetMapping("/login/{userCode}")
    @ResponseBody
    public String checkUserCode(@PathVariable String userCode){
        User user = userService.getUserByCode(userCode);
        // 安全起见, 只返回角色名称 + 图片信息
        return (user != null )  ?
                RestResponse.ok(new HashMap<String, String>(){{
                put("roleName", user.getRole().getRoleName());
                put("img", user.getImg());}}).toJSONString()
                    : RestResponse.fail(SystemCodeEnum.ParameterValidError.getCode(),"用户不存在").toJSONString();
    }
}
